using System;
using System.ComponentModel;
using System.Reflection;

namespace 修为尽失.辅助.exts
{
  
    public static class Converter
    {
        public static T To<T>(this string input)
        {
            try
            {
                var converter = TypeDescriptor.GetConverter(typeof(T));
                return (T) converter.ConvertFromString(input);
            }
            catch (Exception)
            {
                return default;
            }
        }

        public static object To(this string input, Type type)
        {
            try
            {
                var converter = TypeDescriptor.GetConverter(type);
                return converter.ConvertFromString(input);
            }
            catch (Exception)
            {
                return null;
            }
        }
        public static T To<T>(this object obj, T defaultValue = default)
        {
            if (obj == null || obj == DBNull.Value)
                return defaultValue;

            var t = typeof(T);
            if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))    
                t = t.GetGenericArguments()[0];

            var tryParse = t.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder
                , new[] { obj.GetType() , t.MakeByRefType() }
                , new[] { new ParameterModifier(2) });

            if (tryParse != null)
            {
                var parameters = new[] { obj, Activator.CreateInstance(t) };
                bool success = (bool)tryParse.Invoke(null, parameters);
                if (success)
                    return (T)parameters[1];
                return defaultValue;
            }

            return (T)Convert.ChangeType(obj, typeof(T));
        }
        
    }
}